<?php

class HomeController extends BaseController {

	/**
	 * Models used for dashboard statistics
	 */
	protected $userModel;
	protected $fieldModel;
	protected $matchModel;
	
	/**
	 * Controller constructor
	 */
	public function __construct(User $userModel, Field $fieldModel, Match $matchModel) {
		$this->beforeFilter('auth', array('except' => 'showLogin'));
		
		$this->userModel = $userModel;
		$this->fieldModel = $fieldModel;
		$this->matchModel = $matchModel;
	}
	
	/**
	 * Show back-end dashboard
	 * 
	 * @return Response
	 */
	public function showDashboard()
	{
		$usersAmount = $this->userModel->get()->count();
				
		$fieldsAmount = $this->fieldModel->get()->count();
		
		$matchesCreatedAmount = $this->matchModel->count();
		
		$matchesPlayedAmount = $this->matchModel
									->where(
											DB::raw('(select count(*) from match_teams mt
												        inner join team t on mt.teamId = t.id
												        inner join team_users tu on tu.teamId = t.id
												        inner join user u on u.id = tu.userId
												    where  mt.matchId = match_data.id)'), 
											'>=', 
											DB::raw('(select totalPlayers from match_type mty where mty.id = match_data.matchTypeId)')
										)
									->count();
		
		$matchesCancelledAmount = $this->matchModel->where('cancelled', '=', '1')->count();
		
		return View::make('dashboard')
			->with('usersAmount', $usersAmount)
			->with('fieldsAmount', $fieldsAmount)
			->with('matchesCreatedAmount', $matchesCreatedAmount)
			->with('matchesPlayedAmount', $matchesPlayedAmount)
			->with('matchesCancelledAmount', $matchesCancelledAmount);
	}
	
	/**
	 * Show log-in form for un-authenticated users
	 * 
	 * @return Response
	 */
	public function showLogin()
	{
		return View::make('login');
	}

}
